import PyQt5.QtWidgets
from filetype import filetype

import login
import client
import sys
import time,threading
from PyQt5.QtWidgets import QApplication, QMainWindow, QMessageBox
from PyQt5.QtCore import QBasicTimer, Qt

import os,client_code,config
from PyQt5 import QtCore, QtGui, QtWidgets

from register import regist

#选中的文件
selected_filename = " "
selected_row = -1
selected_filename_s = " "
selected_row_s = -1

if __name__ == '__main__':
    app = QApplication(sys.argv)
    win = QMainWindow()
    loginUi = login.Ui_MainWindow()
    clientUi = client.Ui_MainWindow()
    loginUi.setupUi(win)
    loginUi.widget_3.hide()

    #初始化客户端并建立连接
    client = client_code.FTPClient()
    server_ip = config.get_server_ip()
    server_port = config.get_server_port()
    client.connect(server_ip, server_port)

    def change_widget3():
        loginUi.widget_2.hide()
        loginUi.widget_3.show()
    def change_widget2():
        loginUi.widget_3.hide()
        loginUi.widget_2.show()
    def login_button():
        qApp = QApplication.instance()
        if client.login(loginUi.lineEdit.text(), loginUi.lineEdit_2.text()):
            print(f"------welcome! %s------" % loginUi.pushButton.text())
            clientUi.show()
            return True
        else:
            print("-----login failed!-----")
            return False
        clientUi.show()
        #qApp.quit()
    def regist_button():
        if regist(loginUi.lineEdit_3.text(),loginUi.lineEdit_4.text()):
            print("-----注册成功 %s-----" % loginUi.lineEdit_3.text())
            pass
            #弹窗提示注册成功

    #显示用户所有文件信息
    dirpath="./user"
    local=0
    def formatTime(atime):
        import time
        return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(atime))

    for root, dirs, names in os.walk(dirpath):
        for filename in names:
            fileinfo=os.stat(dirpath+"\\"+filename)
            file_type=filename.split(".")[-1]
            item=[filename.split(".")[0],file_type,str(fileinfo.st_size/1024)[0:6] + " kb",formatTime(fileinfo.st_mtime)]
            #添加表格内容
            for j in range(4):
                i = PyQt5.QtWidgets.QTableWidgetItem(item[j])
                clientUi.tableWidget.setItem(local,j,i)
            local+=1

    # 显示服务器所有文件信息
    dirpath_s = "./server"
    local_s = 0
    for root, dirs, names in os.walk(dirpath_s):
        for filename in names:
            fileinfo = os.stat(dirpath_s + "\\" + filename)
            file_type = filename.split(".")[-1]
            item = [filename.split(".")[0], file_type, str(fileinfo.st_size / 1024)[0:6] + " kb", formatTime(fileinfo.st_mtime)]
            # 添加表格内容
            for j in range(4):
                i = PyQt5.QtWidgets.QTableWidgetItem(item[j])
                clientUi.tableWidget_2.setItem(local_s, j, i)
                #item.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
            local_s += 1

    #文件操作,下载、上传、删除
    def selected(row):
        global selected_filename,selected_row
        try:
            selected_filename = clientUi.tableWidget.item(row,0).text()+"."+clientUi.tableWidget.item(row,1).text()
            print(selected_filename)
            selected_row = row
        except:
            pass
            print("未选中内容")
            selected_row = -1
    def selected_s(row):
        global selected_filename_s,selected_row_s
        try:
            selected_filename_s = clientUi.tableWidget_2.item(row,0).text()+"."+clientUi.tableWidget_2.item(row,1).text()
            print(selected_filename_s)
            selected_row_s = row
        except:
            pass
            print("未选中内容")
            selected_row_s = -1
    def upload():
        thread_1 = threading.Thread(target=get_size, name="thread_1")
        thread_1.start()
        thread_2 = threading.Thread(target=upload_son, name="thread_2")
        thread_2.start()
    def upload_son():
        client.put("put " + dirpath + "\\" + selected_filename)
    def download_son():
        client.get("get " + dirpath_s + "\\" + selected_filename_s)
    def download():
        thread_1 = threading.Thread(target=get_size, name="thread_1")
        thread_1.start()
        thread_3 = threading.Thread(target=download_son, name="thread_2")
        thread_3.start()
    def delete():
        global selected_row
        os.remove(dirpath + "/" + selected_filename)
        clientUi.tableWidget.removeRow(selected_row)

    #显示进度
    def set_trans_size():
        clientUi.label_5.setText(f"{client.trans_size}")
        print(f"传输进度：{client.trans_size}%")
    clientUi.label_5.repaint()

    def loop_func(func, second):
        # 每隔second秒执行func函数
        while client.trans_size<100:
            func()
            time.sleep(second)
        clientUi.label_5.setText(f"{client.trans_size}")
    def get_size():
        loop_func(set_trans_size,1)

    #添加槽函数
    loginUi.pushButton.clicked.connect(change_widget2)
    loginUi.pushButton_2.clicked.connect(change_widget3)
    loginUi.pushButton_3.clicked.connect(login_button)
    loginUi.pushButton_5.clicked.connect(regist_button)

    clientUi.pushButton_2.clicked.connect(upload)
    clientUi.pushButton_3.clicked.connect(download)
    clientUi.pushButton_4.clicked.connect(delete)
    # 表格选中文件
    clientUi.tableWidget.cellPressed.connect(selected)
    clientUi.tableWidget_2.cellPressed.connect(selected_s)

    win.show()
    sys.exit(app.exec_())